package com.arges.web.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.arges.web.common.Constant;
import com.arges.web.common.GsonUtils;
import com.arges.web.domain.bean.PictureBean;
import com.arges.web.domain.pojo.Picture;
import com.arges.web.page.PageInfo;
import com.arges.web.page.WebUtils;
import com.arges.web.service.PatManager;
import com.arges.web.service.PictureManager;

/**
 * 患者图像控制层
 * 
 * @author zxj
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/picture")
public class PictureController
{

	@Autowired
	private PatManager patManager;

	@Autowired
	private PictureManager pictureManager;

	/**
	 * 储存用户头像
	 * 
	 * @param file
	 * @param request
	 * @param response
	 */
	@RequestMapping("/savePhoto.do")
	@ResponseBody
	public String saveUserPhoto(HttpServletRequest request, HttpServletResponse response)
	{
		String mrn = request.getParameter("mrn");
		String memo = request.getParameter("memo");
		String p_date_String = request.getParameter("p_date_String");
		String pictureName = "";
		PictureBean pictureBean = new PictureBean();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = null;
		file = multipartRequest.getFile("picture");
		String fileName = file.getOriginalFilename();
		String savePath = request.getServletContext().getRealPath("");
		// 获取tomcat目录
		String realPath = savePath.substring(0, savePath.lastIndexOf("webapps") + 7) + "/upload/Pat/picture/";
		String result = "";
		try
		{
			// 获取上传文件的原始名字
			if (StringUtils.isNotBlank(fileName))
			{
				// 将文件装换为io文件类型
				File file2 = new File(fileName);
				file.transferTo(file2);
				String prefix = fileName.substring(fileName.lastIndexOf("."));
				String newFileName = new Date().getTime() + prefix;
				FileUtils.copyFile(file2, new File(realPath, newFileName));
				pictureName = newFileName;
				// result = "{\"result\":\"SUCCESS\",\"path\":\"" + newFileName + "\"}";
				result = "SUCCESS";

			}
			else
			{
				result = "NULL";
			}
		}
		catch (Exception e)
		{
			result = "ERROR";
		}
		// try
		// {
		// response.getWriter().write(result);
		// }
		// catch (IOException e)
		// {
		// e.printStackTrace();
		// }

		if (result.equals("SUCCESS"))
		{
			pictureBean.setMrn(mrn);
			pictureBean.setMemo(memo);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try
			{
				Date date = sdf.parse(p_date_String);
				pictureBean.setDate(date);
			}
			catch (ParseException e)
			{
				e.printStackTrace();
			}
			if (null != pictureBean.getId())
			{
				pictureBean.setPicture(pictureName);
				Picture picture = new Picture();
				BeanUtils.copyProperties(pictureBean, picture);
				pictureManager.update(picture);
				result = "SUCCESS";
			}
			else
			{
				pictureBean.setPicture(pictureName);
				Picture picture = new Picture();
				BeanUtils.copyProperties(pictureBean, picture);
				pictureManager.save(picture);
				result = "SUCCESS";
			}

		}
		return result;

	}

	@RequestMapping(value = "/deletePictureById.do")
	@ResponseBody
	public String deletePictureById(HttpServletRequest request)
	{
		String result = Constant.SUCCESS;
		String id = request.getParameter("id");
		String savePath = request.getServletContext().getRealPath("");
		String realPath = savePath.substring(0, savePath.lastIndexOf("webapps") + 7) + "/upload/Pat/picture/";
		try
		{
			if (StringUtils.isNotBlank(id))
			{
				PictureBean pictureBean = new PictureBean();
				pictureBean = pictureManager.getpicture(Long.valueOf(id));
				if (null != pictureBean)
				{
					File file = new File(realPath + pictureBean.getPicture());
					file.delete();
				}
				pictureManager.delete(pictureBean.getId());
			}
		}
		catch (Exception e)
		{
			result = Constant.ERROR;
		}

		return result;
	}

	/**
	 * 根据路径删除用户头像
	 * 
	 * @param realPath
	 * @param user
	 */
	@SuppressWarnings("unused")
	private void deleteOldPicture(String realPath)
	{
		File oldFile = new File(realPath);
		oldFile.delete();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getPatPictureList.do")
	public String getPatPictureList(HttpServletRequest request, ModelMap map)
	{
		PageInfo<PictureBean> pageInfo = null;
		String mrn = request.getParameter("mrn");
		String pageinfoString = request.getParameter("PicturePageInfo");
		if (StringUtils.isBlank(mrn))
		{
			mrn = "";
		}
		if (StringUtils.isNotBlank(pageinfoString))
		{
			pageInfo = GsonUtils.stringToObject(pageinfoString, PageInfo.class);
		}
		else
		{
			pageInfo = new PageInfo<PictureBean>();
		}

		pageInfo.setOrderByName("date");
		pageInfo.setOrder("asc");
		PageInfo<Picture> pojoInfo = WebUtils.beanToPojoPage(pageInfo, Picture.class);
		pageInfo = pictureManager.getPagePicture(pojoInfo, mrn);

		String savePath = request.getServletContext().getRealPath("");
		// 获取tomcat目录
		String realPath = savePath.substring(0, savePath.lastIndexOf("webapps") + 7) + "/upload/Pat/picture/";

		map.put("chaxun", mrn);
		map.put("pictureBeanList", pageInfo.getResult());
		pageInfo.setResult(null);
		map.put("picturePageInfo", GsonUtils.objectToJson(pageInfo));
		map.put("realPath", realPath);
		return "pat/picture";
	}

	@RequestMapping(value = "/getPictureById.do")
	@ResponseBody
	public PictureBean getPictureById(HttpServletRequest request)
	{
		String id = request.getParameter("id");
		PictureBean pictureBean = null;
		if (StringUtils.isNotBlank(id))
		{
			pictureBean = pictureManager.getpicture(Long.valueOf(id));
		}
		return pictureBean;
	}

	@RequestMapping(value = "/getPictureBeans.do")
	@ResponseBody
	public List<PictureBean> getPictureBeans(HttpServletRequest request)
	{

		String mrn = request.getParameter("mrn");
		List<PictureBean> list = null;
		if (StringUtils.isNotBlank(mrn))
		{
			list = pictureManager.getpictureList(mrn);
		}
		return list;
	}

}
